package com.lw.leetcode.add.e;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 803. 打砖块
 *
 * @author liw
 * @version 1.0
 * @date 2022/6/25 21:04
 */
public class HitBricks {

    public static void main(String[] args) {
      HitBricks test = new HitBricks();

        // [2]
//        int[][] grid = {{1, 0, 0, 0}, {1, 1, 1, 0}};
//        int[][] hits = {{1, 0}};

        // [0, 0]
//        int[][] grid = {{1, 0, 0, 0}, {1, 1, 0, 0}};
//        int[][] hits = {{1, 1}, {1, 0}};

        // [0, 0]
//        int[][] grid = {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}};
//        int[][] hits = {{3, 2}, {2, 3}, {2, 1}, {1, 2}, {2, 0}, {0, 1}, {1, 0}};
//        int[][] hits = {{0, 1},{0, 2},{0, 3}, {1, 0}};

        // [0, 0]
        int[][] grid = {{1, 1, 1, 1}, {1, 0, 0, 0}, {0, 1, 1, 1}, {1, 1, 1, 1}};
        int[][] hits = {{2,0}};
//        int[][] hits = {{0, 1},{0, 2},{0, 3}, {1, 0}};

        int[] ints = test.hitBricks(grid, hits);
        System.out.println(Arrays.toString(ints));

    }

    private int[][] grid;
    private int m;
    private int n;
    private int[][] arr = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};

    public int[] hitBricks(int[][] grid, int[][] hits) {
        this.m = grid.length;
        this.n = grid[0].length;
        this.grid = grid;
        int length = hits.length;
        int[] values = new int[length];
        for (int i = 0; i < length; i++) {
            int a = hits[i][0];
            int b = hits[i][1];
            if (grid[a][b] == 0) {
                values[i] = 0;
                continue;
            }
            grid[a][b] = 0;
            for (int[] ints : arr) {
                int w = a + ints[0];
                int v = b + ints[1];
                boolean boo = find(w, v);
                if (boo) {
                    chenge(w, v, 3, 2);
                } else {
                    values[i] += chenge(w, v, 0, 2);
                }
            }
            for (int[] ints : arr) {
                int w = a + ints[0];
                int v = b + ints[1];
                chenge(w, v, 1, 3);
            }
        }
        return values;
    }

    private boolean find(int a, int b) {
        if (a < 0 || b < 0 || a == m || b == n || grid[a][b] == 0 || grid[a][b] == 2) {
            return false;
        }
        if (a == 0 || grid[a][b] == 3) {
            return true;
        }
        grid[a][b] = 2;
        for (int[] ints : arr) {
            if (find(a + ints[0], b + ints[1])) {
                return true;
            }
        }
        return false;
    }

    private int chenge(int a, int b, int v, int d) {
        if (a < 0 || b < 0 || a == m || b == n || grid[a][b] != d) {
            return 0;
        }
        int sum = 1;
        grid[a][b] = v;
        for (int[] ints : arr) {
            sum += chenge(a + ints[0], b + ints[1], v, d);
        }
        return sum;
    }

}
